package com.lixinwen.gdgame.game;

import com.google.gson.Gson;
import com.lixinwen.gdgame.game.room.RoomContext;
import com.lixinwen.gdgame.vo.RoomVo;
import com.lixinwen.gdgame.vo.res.AIRes;
import com.lixinwen.gdgame.vo.res.HumanRes;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RoomManager {

    private Map<Session,Integer> map = new ConcurrentHashMap<>();
    private Map<Integer, ArrayList<Session>> rooms = new ConcurrentHashMap<>();
    private Map<Integer, RoomContext> roomInfo = new ConcurrentHashMap<>();

    public void handleNewConn(Session session, RoomVo roomVo) {
        if(!rooms.containsKey(roomVo.getRoom())){
            this.createNewRoomContext(roomVo.room);
        }
        this.handleSeat(session,roomVo.room,roomVo.seat);
    }

    public void handleMessage(Session session, String message) {
        Gson g = new Gson();
        RoomContext ctx = roomInfo.get(map.get(session));
        if(message.contains("AIRes")){
            AIRes res = g.fromJson(message, AIRes.class);
            ctx.handleRes(res);
        }
        else if(message.contains("HumanRes")){
            HumanRes res = g.fromJson(message, HumanRes.class);
            ctx.handleRes(res);
        }
    }

    private void createNewRoomContext(int room){
       RoomContext ctx = new RoomContext();
       roomInfo.put(room,ctx);
       rooms.put(room,new ArrayList<>());
    }

    private void handleSeat(Session session,int room,int seat){
        rooms.get(room).add(session);
        roomInfo.get(room).takeSeat(session,seat);
    }
}
